<?php
	/**
	 * Spherus Online editor
	 * 
	 * @author Rossoft LTD
	 * @package classes
	 * @version 1.0
	 */
	class SpherusFileEditor
	{
		static $externalFunctionDescriptionPlaceholderId = 'functionDescriptionPlaceholder';
		
		/**
		 * Spherus PHP functions highlight string
		 *
		 * @var string
		 */
		static $highlightFunctionString = '';
		
		/**
		 * Array with the functions
		 *
		 * @var string
		 */
		static $functionsString = array();
		
		/**
		 * Functions' descriptions
		 *
		 * @var array
		 */
		static $functionsDescription = array();
		
		
		/**
		 * Loads online editor
		 *
		 * @param string $contents edit area contents
		 * @param array $options options for the editor (id, ...)
		 */
		static function LoadEditor($contents, array $options, $textarea_name = 'content', $path_to_file = '')
		{
			global $current_controller;
			
			//load editor JS file
			echo '<script language="JavaScript" type="text/javascript" src="/spherus_framework/core/classes/SpherusFileEditor/edit_area_loader.js"></script>';
						
			//sets the SpherusPHP toolbar
			self::SetSpherusPHPToolbar();
			
			//sets the HTML toolbar
			self::SetHTMLToolbar($path_to_file);
			
			//sets the PHP toolbar
			self::SetPHPToolbar();
			
			//string with the options for the OnlineEditor
			$options_string = '';
			foreach ($options as $key => $value)
			{
				$options_string .= "$key: '$value', ";
			}
			
			//initializes OnlineEditor
			$current_controller->helpers->html->JavaScript("editAreaLoader.init({".$options_string."});");

			$current_controller->helpers->html->form('', 'post', 'id = "filesource_form" onsubmit = "savefile(document.getElementById(\'path_to_file\').value, document.getElementById(\'file_source\').value, \''.$current_controller->name.'\'); return false;"');
			$current_controller->helpers->html->Textarea($textarea_name, $contents, 'id="'.$options[id].'" style="height: 617px; width: 100%;"');

			$current_controller->helpers->html->hidden('path_to_file', $path_to_file, "id = 'path_to_file'");
			echo "<input type = 'submit' value = 'save' name = 'filesource_submit' id = 'filesource_submit' style = 'display: none' /></form>";
		}
		
		/**
		 * Table for displaying function description.
		 *
		 * @param string $table_html_attributes html attributes for the description table
		 * @param string $header_html_attributes html attributes for the description table header
		 * @param string $content_html_attributes html attributes for the description table content
		 */
		static function FunctionDescriptionBlock($table_html_attributes, $header_html_attributes, $content_html_attributes)
		{
			echo
			"
			 	<table $table_html_attributes id = 'functionDescriptionBlock'>
					<tr>
						<td $header_html_attributes>".ucfirst(LANG_FUNCTION_DETAILS)."</td>
					</tr>
					<tr>
						<td $content_html_attributes id = 'functionDescriptionPlaceholder'>".LANG_FUNCTION_DETAILS_HERE."...</td>
					</tr>
				</table>			
			";
		}
		
		/**
		 * Creates a block (table) with the functions divided by classes
		 *
		 * @param array $functions functions array
		 */
		static function FileFunctionsListBlock(array $functions = array())
		{
			if (empty($functions)) return;
			
			$functions_tree = array();
			$functions_tree[current_file][name] = ucfirst(LANG_FUNCTIONS_LIST);
			
			echo "<table>";
			foreach ($functions as $key => $value)
			{
				$functions_tree[current_file][sub][$key][name] = $key;
				$functions_tree[current_file][sub][$key][url] = '\" onMouseOver = "" onClick = "/*this.style.fontWeight = \\\'bold\\\';*/ editorDocument = document.getElementById(\\\'frame_file_source\\\').contentDocument; editorDocument.getElementById(\\\'search\\\').click(); editorDocument.getElementById(\\\'area_search_replace\\\').display = \\\'none\\\'; editorDocument.getElementById(\\\'area_search\\\').value = \\\'class \\\' + this.lastChild.nodeValue.split(\\\'(\\\')[0]; editorDocument.getElementById(\\\'area_search_button\\\').click(); editorDocument.getElementById(\\\'area_search\\\').value = \\\'\\\'; editorDocument.getElementById(\\\'close_search_button\\\').click(); return false;" onkeyup=\" ';
				foreach ($value as $function)
				{
					$functions_tree[current_file][sub][$key][sub][$function[full_name]][name] = $function[full_name];
					$functions_tree[current_file][sub][$key][sub][$function[full_name]][url] = '\" onMouseOver = "" onClick = "/*this.style.fontWeight = \\\'bold\\\';*/ editorDocument = document.getElementById(\\\'frame_file_source\\\').contentDocument; editorDocument.getElementById(\\\'search\\\').click(); /*editorDocument.getElementById(\\\'area_search_replace\\\').style.display = \\\'none\\\';*/ search_value = \\\'function \\\' + this.lastChild.nodeValue.split(\\\'(\\\')[0]; editorDocument.getElementById(\\\'area_search\\\').value = search_value; editorDocument.getElementById(\\\'area_search_button\\\').click(); editorDocument.getElementById(\\\'area_search\\\').value = \\\'\\\'; editorDocument.getElementById(\\\'close_search_button\\\').click(); return false" onkeyup=\" ';
				}
			}
			echo TreeMenu::CreateMenu($functions_tree, array('node'=>'class.gif', 'node_open'=>'class.gif', 'leaf'=>'function.gif'));
		}
		
		/**
		 * Converts function list from many files to the JS variable which contains HTML options collection and sets JS variable which contains function highlight syntax
		 *
		 * @param string $name js variable name
		 * @param array $functions functions array to be parsed
		 * @param string $prefix string to be used before the option value
		 * @param string $postfix string to be used after the option value
		*/
		static function MultiFileFunctionsToHTMLOptions($name, array $file_functions, $prefix = '', $postfix = '', $separator = '')
		{
			global $current_controller;
			
			self::$functionsString[$name] = '';
			foreach ($file_functions as $key=>$value)
			{
				self::FunctionsToHTMLOptions($name, $key, $value, $prefix.$key.$separator, $postfix);
			}
		}
		
		/**
		 * Converts function list to the JS variable which contains HTML options collection and sets JS variable which contains function highlight syntax
		 *
		 * @param string $name js variable name
		 * @param array $functions functions array to be parsed
		 * @param string $prefix string to be used before the option value
		 * @param string $postfix string to be used after the option value
		 */
		static function FunctionsToHTMLOptions($name, $key, array $functions, $prefix = '', $postfix = '')
		{
			global $current_controller;
			
			//generate functions options for the dropdown list and functions list for the syntax highlight
			self::$functionsString[$name] .= "<option onClick = 'parent.document.getElementById(\\\"".self::$externalFunctionDescriptionPlaceholderId."\\\").innerHTML = \\\"".ucfirst(LANG_FUNCTION_DETAILS_HERE)."...\\\";' value = '-1' class = 'toolbar_header'>- $key -</option>";
			foreach ($functions as $k => $v)
			{
				foreach ($v as $function)
				{
					//if the functiom has parameters
					if (!empty($function[params]))
					{
						$params_string = '';
						foreach ($function[params] as $param)
						{
							$params_string .= $param[name].', ';
						}
						$params_string = substr($params_string, 0, strlen($params_string)-2);
					}
					else
					{
						$params_string = '';
					}
					
					//generate option
					self::$functionsString[$name] .= "<option onClick = 'descriptionBox = parent.document.getElementById(\\\"".self::$externalFunctionDescriptionPlaceholderId."\\\"); descriptionBox.innerHTML = this.label;' class = 'toolbar' label = '".$function[class_name_string].$function[location].$function[comment][description_string].$function[comment][parameters_string].$function[comment][returns_string]."' title = '".$function[comment][description]."' value='".$prefix.$function[name]."(".$params_string.")".$postfix."'>".$function[name]."</option>";
					
					//add to highlight array
					self::$highlightFunctionString .= "'".$function[name]."', ";
				}
			}
		}
		
		/**
		 * Sets SpherusPHPToolbar
		 *
		 */
		static function SetSpherusPHPToolbar()
		{
			global $current_controller;
			
			if (empty($_SESSION[spherusPHPToolbar]))
			{
				//helper functions list box generation
				$appHelperFunctions = File::GetFunctionsList("./app/includes/helpers");
				self::MultiFileFunctionsToHTMLOptions('application_helpers', $appHelperFunctions, '$this->helpers->', ';', '->');
	
				$coreHelperFunctions = File::GetFunctionsList("./spherus_framework/core/helpers");
				self::MultiFileFunctionsToHTMLOptions('framework_helpers', $coreHelperFunctions, '$this->helpers->', ';', '->');
				
				//core classes functions list box generation
				$coreFunctions = File::GetFunctionsList("./spherus_framework/core/classes");
				self::MultiFileFunctionsToHTMLOptions('core', $coreFunctions, '', ';', '::');
	
				//shows function description block
				$current_controller->helpers->html->JavaScript('parent.document.getElementById("functionDescriptionBlock").style.display = ""');
				
				//defines Spherus Function Highlight array
				$current_controller->helpers->html->JavaScript("spherus_function_highlight = new Array(".substr(self::$highlightFunctionString, 0, strlen(self::$highlightFunctionString)-2).")");
				$_SESSION[highlightFunctionString] = self::$highlightFunctionString;
				
				$spherusPHPToolbar = "<table cellpadding='0' cellspacing='0' style='border: 0px;'>";
				foreach (self::$functionsString as $key=>$value)
				{
					$spherusPHPToolbar .= "<tr><td style = ''><table cellpadding = '0' cellspacing = '0' class = 'toolbar' id = '$key'><tr><td align = 'left' valign = 'middle'><img src = '/spherus_framework/core/classes/SpherusFileEditor/images/plus.gif' id = '{$key}ToolbarsImage' onClick = 'ShowHideElement(\\\"{$key}Toolbars\\\", \\\"{$key}ToolbarsImage\\\", \\\"plus.gif\\\", \\\"minus.gif\\\")' /> $key</td></tr><tr><td><div id = '{$key}Toolbars' style = 'display: none'><select style = 'width: 100%' size = '10' id='{$key}_select' ondblclick='javascript:editArea.execCommand(\\\"insert_construction\\\", this.id); selection_end = parent.editAreaLoader.getSelectionRange(\\\"file_source\\\").end; parent.editAreaLoader.setSelectionRange(\\\"file_source\\\", selection_end, selection_end)' fileSpecific='no'>";
					$spherusPHPToolbar .= self::$functionsString[$key];
					$spherusPHPToolbar .= "</select></div></td></tr></table></td></tr>";
				}
				$spherusPHPToolbar .= '</table>';
				
				$_SESSION[spherusPHPToolbar] = $spherusPHPToolbar;
			}
			else
			{
				$spherusPHPToolbar = $_SESSION[spherusPHPToolbar];
				self::$highlightFunctionString = $_SESSION[highlightFunctionString];
			}
			
			//shows function description block
			$current_controller->helpers->html->JavaScript('parent.document.getElementById("functionDescriptionBlock").style.display = ""');
			
			//defines Spherus Function Highlight array
			$current_controller->helpers->html->JavaScript("spherus_function_highlight = new Array(".substr(self::$highlightFunctionString, 0, strlen(self::$highlightFunctionString)-2).")");
			
			$current_controller->helpers->html->JavaScript('spherusPHP_toolbar = "<div id = \'syntax_toolbars\'>'.$spherusPHPToolbar.'</div>"');			
		}

		/**
		 * Sets HTMLToolbar
		 *
		 */
		static function SetHTMLToolbar($path_to_file)
		{
			global $current_controller;
			
			$HTMLToolbar = "<table cellpadding='0' cellspacing='0' style='border: 0px;'>";
			$HTMLToolbar .= "<a class = '' href = '/spherus_framework/core/classes/SpherusFileEditor/htmleditor/abitwhizzy.php?path_to_file=$path_to_file'>".ucfirst(LANG_OPEN_WYSIWYG)."</a>";
			$HTMLToolbar .= '</table>';
			$current_controller->helpers->html->JavaScript('HTML_toolbar = "<div id = \'syntax_toolbars\'>'.$HTMLToolbar.'</div>"');			
		}

		/**
		 * Sets PHPToolbar
		 *
		 */
		static function SetPHPToolbar()
		{
			global $current_controller;
			
			$PHPToolbar = "<select id='syntax_toolbars' onchange='javascript:editArea.execCommand(\\\"insert_construction\\\", this.id)' fileSpecific='no'>"
							."			<option value='-1'>Select...</option>";
			$PHPToolbar .= "<option value='if () \\n{\\n\\t{text}\\n}\\n'>if</option>"
							."			<option value='foreach (\$elements as \$key=>\$value) \\n{\\n\\t{text}\\n}\\n'>foreach</option>"
							."			<option value='switch ({text}) \\n{\\n\\tcase \\\"\\\": break;\\n\\tcase \\\"\\\": break;\\n\\tdefault:\\n}\\n'>switch/case</option>"
							."			<option value='/*\\n * {\$comment_here}\\n*/\\nfunction func_name() \\n{\\n\\t{text}\\n}\\n'>function</option>"
							."			<option value='/*{text}*/'>block comment</option>"
							."			<option value='//{text}'>inline comment</option>"
							."		</select>";
			$current_controller->helpers->html->JavaScript('PHP_toolbar = "<div id = \'syntax_toolbars\'>'.$PHPToolbar.'</div>"');			
		}
		
		
		/**
		 * NOT USED: Loads online editor row with the label
		 *
		 * @param string $label editor label
		 * @param string $contents edit area contents
		 * @param array $options options for the editor (id, ...)
	    */
		static function LoadEditorRow($label, $textarea_name, $contents, array $options)
		{
			echo "<tr><td>$label</td><td>";
			self::LoadEditor($contents, $options, $textarea_name);
			echo "</td><td>&nbsp;</td></tr>";
		}
	}
?>